import axios from 'axios'
import qs from 'qs'
import router from '../router'
axios.defaults.timeout = 6000000000 // 响应时间
axios.defaults.baseURL = '/admin' // 配置接口地址
let noQsJson = [
    '/trade/updateActivitySort',
    '/ad/saveUpdateVideo',
    '/home/updateHomePage',
    '/home/updateChannel',
    '/home/addChannel',
    '/home/updateTopic',
    '/home/addTopic',
    '/game/addGame',
    '/game/updateGame',
    '/game/createGameCategory',
    '/game/updateGameCategory',
    '/game/createGameTag',
    '/game/updateGameTag',
    '/game/updateGameCategorySort',
    '/game/updateRankWeight',
    '/video/updateGameVideo',
    '/video/addGameVideo',
    '/spider/gameCollectFirst',
    '/spider/applicationTreasureFirstStep',
    '/spider/gameInfoInsert',
    '/spider/videoRule',
    '/spider/updateRule',
    '/spider/updateCollectVideo',
    '/video/addVideoCategory',
    '/video/updateVideoCategory',
    '/task/updateInviteTask',
    '/task/updateGameTask',
    '/order/updateAdmoreUserInfo',
    '/withdraw/updateStatus',
    '/file/uploadPicByUrl',
    '/apkManage/saveApk',
    '/apkManage/saveChannel',
    '/lottrey/updateActivityInfo',
    '/lottrey/addMoudle',
    '/lottrey/updateBoxActivityVo',
    '/exam/updateQuestionInfo',
    '/gameList/createCollectionList',
    '/gameList/updateCollectionStatus',
    '/trade/updateActivityCategorySort',
    '/trade/updateWZRYSkin',
    '/trade/updateHotSkinSort',
    '/team/getTeamUserInfo',
    '/trade/updateWzydHeroInfo',
    '/team/updateIdentity',
    '/team/updateOpenReward',
    '/team/kingApplies',
    '/team/operateKingApplies',
    '/team/complaintList',
    '/team/operateComplaint',
    '/team/setTeamKingStatus',
    '/trade/editScreenNoticeSort',
    'trade/operateScreenNoticeStatus',
    '/trade/createScreenNotice',
    '/peace/updatePeaceSkinInfo',
    '/peace/updatePeaceSelectorLabelSort',
    '/peace/selectAccountManageView',
    '/peace/selectPropView',
    '/peace/addPeaceSkin',
    '/peace/operatePropAuditStatus',
    '/peace/editPropView',
    '/peace/selectAccountIncome',
    '/peace/operateAccountManageStatus',
    '/deal/operateDealStatus',
    '/black/addTradeAccountBlack',
    '/black/updateTradeAccountBlack',
    '/thirdOrder/createOrder',
    '/thirdOrder/thirdOrders',
    '/thirdOrder/cancelOrder',
    '/thirdOrder/addTime',
    '/thirdOrder/refundOrder',
    '/thirdOrder/thirdOrderDetail',
    '/peace/updatePeaceTypeSort',
    '/rentPrice/updateAccountPrice',
    '/api/deal/wzSelector',
    '/thirdOrder/saveUpdateGoodsMatchRule',
    '/thirdOrder/goodsMatchRules',
    '/trade/sortBanner',
    '/user/addRemark',
    '/user/delRemark',
    '/user/editRemark',
    '/user/getUserView',
    '/user/getUserBindInfoVersion2',
    'user/manageAccounts',
    '/deal/userDealOrderList',
    '/data/selectUserDetailData',
    '/data/selectOrderDetailV1',
    '/deal/changePrice',
    '/user/adviseUsers',
    '/user/userRefundRecharge',
    '/user/adviseUserView',
    '/user/adviseUserSelHistory',
    '/user/adviseUserManageAccount',
    '/user/adviseUserTapCount',
    '/user/adviseUserBuyTapCount',
    '/user/adviseUserViewTapCount',
    'trade/gamePlugConfAdd',
    'trade/gamePlugConfUpdate',
    'trade/gamePlugConfDelete',
    '/account/createAdminRole',
    '/account/addUserToRoles',
    '/account/createMenus',
    // '/peace/updatePeaceTypeInfo',
    // '/peace/addPeaceType'
]
axios.interceptors.request.use(config => {
    // 兼容H5筛选器的接口
    if (config.url === '/deal/wzSelector') {
        config.baseURL = '/api' // 配置接口地址
    }
    if (config.method === 'post') {
        let contentType = config.headers['Content-Type']
        if (contentType && contentType.toLowerCase() === 'multipart/form-data') {
            // 原生表单提交，不处理默认
        } else {
            // json 提交 处理
            config.data = noQsJson.includes(config.url) ? config.data : qs.stringify(config.data)
        }
    }
    return config
}, (error) => {
    console.log(error)
    return Promise.reject(error)
})

// 添加一个响应拦截器
axios.interceptors.response.use(response => {
    const responseCode = response.status
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    if (responseCode === 200) {
        if (response.data.code === '40002' || response.data.code === '40004' || response.data.code === '40006') {
            router.replace('/login')
        }
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response)
    }
}, error => {
    // 断网 或者 请求超时 状态
    if (!error.response) {
    // 请求超时状态
        if (error.message.includes('timeout')) {
            console.log('超时了')
        } else {
            // 可以展示断网组件
            console.log('断网了')
        }
        return
    }
    // 服务器返回不是 2 开头的情况，会进入这个回调
    // 可以根据后端返回的状态码进行不同的操作
    const responseCode = error.response.status

    switch (responseCode) {
    // 401：未登录
    case 401:
        console.log('跳转登录页')
        // 跳转登录页
        // router.replace({
        //   path: '/login',
        //   query: {
        //     redirect: router.currentRoute.fullPath
        //   }
        // })
        break
    // 403: token过期
    case 403:
        console.log('登录信息过期，请重新登录')
        // 清除token
        // localStorage.removeItem('token')
        // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
        // setTimeout(() => {
        //   router.replace({
        //     path: '/login',
        //     query: {
        //       redirect: router.currentRoute.fullPath
        //     }
        //   })
        // }, 1000)
        break
    // 404请求不存在
    case 404:
        console.log('网络请求不存在')
        break
    // 其他错误，直接抛出错误提示
    default:
        alert('服务器异常，请稍后再试')
        console.log(error.response.data.message)
    }
    return Promise.reject(error)
})

// httpReq.install = function (Vue) {
//     Vue.prototype.$http = axios
// }
// 1. 作为vue 的插件挂载在vue组件的this实例上
// 2. 在公用的接口请求模块使用

export const $http = axios
